using System;

using Pegasus.Diagnostics;
using Pegasus.Workflow.Service;

namespace Pegasus.UnitTests.Workflow.Service.Workflows
{
	public class StateTimer : WorkflowState
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="T:StateTimer"/> class.
		/// </summary>
		public StateTimer() :
			base( "StateTimer" )
		{
		}

		/// <summary>
		/// Called when the state is entered.
		/// </summary>
		/// <param name="previousState">Previouse state, null if workflow is just starting.</param>
		protected override void OnStateEnter( string previousState )
		{
			base.OnStateEnter( previousState );

			Workflow.RegisterTimer( DateTime.Now.AddMilliseconds( 500 ), 
				new EventHandler<WorkflowEventArgs>( TimerEvent ),
				this, new TestingEventArgs( Workflow.WorkflowId, 160, true ) );
		}

		/// <summary>
		/// Timers the event.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="args">The <see cref="T:Pegasus.Workflow.Service2.WorkflowEventArgs"/> instance containing the event data.</param>
		private void TimerEvent( object sender, WorkflowEventArgs args )
		{
			int count = 0;

			if( Workflow.Context.ContainsKey( "TimerCount" ) )
			{
				count = (int) Workflow.Context[ "TimerCount" ];
			}

			// Make sure we have the proper sender object
			if( sender == null )
			{
				Workflow.WorkflowComplete( -3 );
				return;
			}

			// Make sure the we have the proper args values
			if( args is TestingEventArgs )
			{
				if( ( (TestingEventArgs) args ).AnotherValue != 160 )
				{
					Workflow.WorkflowComplete( -2 );
					return;
				}
			}
			else
			{
				Workflow.WorkflowComplete( -1 );
				return;
			}


			count++;
			if( count < 5 )
			{
				Workflow.Context[ "TimerCount" ] = count;

				// Reschedule the workflow
				Workflow.RegisterTimer( DateTime.Now.AddMilliseconds( 500 ),
					new EventHandler<WorkflowEventArgs>( TimerEvent ),
					this, new TestingEventArgs( Workflow.WorkflowId, 160 ) );
			}
			else
			{
				Workflow.WorkflowComplete( 10 );
			}
		}
	}
}
